package yams.resource.impl;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import yams.common.InfoPage;
import yams.common.constants.*;
import yams.domain.*;
import yams.resource.IMobileHomeResource;
import yams.resource.JsonCommonResource;
import yams.response.JsonResponse;
import yams.response.Response;
import yams.service.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by LX on 2017/7/21.
 */
@RestController
@RequestMapping("/mobileHomePage")
public class DefaultMobileHomeResource extends JsonCommonResource implements IMobileHomeResource{

    @Resource
    private IHouseService houseService;
    @Resource
    private IContractService contractService;
    @Resource
    private IRepairService repairService;
    @Resource
    private ICleanService cleanService;
    @Resource
    private ICheckmeterService checkmeterService;
    @Resource
    private IUserInspectionService userInspectionService;
    @Resource
    private IBillService billService;
    @Resource
    private IUserService userService;

    /**
     * 移动端首页展现
     * @param emptyEntity
     * @return
     */
    @RequestMapping(value = "/", method = RequestMethod.POST)
    @Override
    public  Response<MobileHomePageInfo> mobileHomePage(@RequestBody EmptyEntity emptyEntity){
        MobileHomePageInfo homePageInfo = new MobileHomePageInfo();
        HouseEntity houseEntity = new HouseEntity();
        /*房屋总数*/
        homePageInfo.setTotalHouseCnt(houseService.count(houseEntity));
        /*空房数*/
        houseEntity.getProperties().put("status", HouseStatusEnum.EMPTY.getValue());
        homePageInfo.setEmptyHouseCnt(houseService.count(houseEntity));
        /*已出租*/
        houseEntity.getProperties().put("status", HouseStatusEnum.CHECKED.getValue());
        homePageInfo.setRentedHouseCnt(houseService.count(houseEntity));
        /*即将到期*/
        ContractEntity contractCondition1 = new ContractEntity();
        contractCondition1.getProperties().put("endDate_gt", Date.from(LocalDateTime.now()
                .atZone(ZoneId.systemDefault()).toInstant()));
        contractCondition1.getProperties().put("endDate_le", Date.from(LocalDateTime.now().plusDays(5)
                .atZone(ZoneId.systemDefault()).toInstant()));
        homePageInfo.setCheckoutHouseCnt(contractService.count(contractCondition1));
        /*超期账单*/
        ContractEntity contractCondition2 = new ContractEntity();
        contractCondition2.getProperties().put("nextPayDate_gt", LocalDate.now().toString());
        contractCondition2.getProperties().put("nextPayDate_le", LocalDate.now().plusDays(5).toString());
        homePageInfo.setOverdueBillCnt(contractService.count(contractCondition2));

        /*抄表处理 当月未抄表*/
        CheckmeterEntity checkmeterCondition = new CheckmeterEntity();
        checkmeterCondition.getProperties().put("status", ContractStatusEnum.EXECUTING.getValue());
        checkmeterCondition.getProperties().put("meterYear", String.valueOf(LocalDateTime.now().getYear()));
        checkmeterCondition.getProperties().put("meterMonth",String.valueOf(LocalDateTime.now().getMonthValue()));
        checkmeterCondition.getProperties().put("pageNumber", 0);
        checkmeterCondition.getProperties().put("pageSize", 9999);
        InfoPage<CheckmeterEntity> page = new InfoPage<CheckmeterEntity>();
        page = checkmeterService.filterCheckmeter(checkmeterCondition);
        homePageInfo.setCheckMeterCnt(page.getTotal());
        /*报修处理*/
        RepairCallEntity repairCondition = new RepairCallEntity();
        repairCondition.getProperties().put("status", RequestStatusEnum.TODO.getValue());
        homePageInfo.setRepairCnt(repairService.count(repairCondition));
        /*保洁处理*/
        CleanEntity cleanCondition = new CleanEntity();
        cleanCondition.getProperties().put("status", RequestStatusEnum.TODO.getValue());
        homePageInfo.setCleanCnt(cleanService.count(cleanCondition));
        /*预约看房*/
        UserInspectionEntity makeAppointCondition = new UserInspectionEntity();
        makeAppointCondition.getProperties().put("orderStatus", InspectionOrderStatusEnum.TODO.getValue());
        homePageInfo.setMakeAppointmentCnt(userInspectionService.count(makeAppointCondition));
        /*账单管理*/
        BillEntity billCondition=new BillEntity();
        billCondition.getProperties().put("status", BillStatusEnum.UNPAID.getValue());
        homePageInfo.setBillCnt(billService.count(billCondition));
        /*会员管理*/
        UserEntity userCondition=new UserEntity();
        userCondition.getProperties().put("certification",2);
        homePageInfo.setUserCnt(userService.count(userCondition));

        return JsonResponse.buildSingle(homePageInfo);
    }



    /**
     * 与房屋相关的查询
     * @param emptyEntity 过滤条件
     * @return
     */

    @RequestMapping(value = "/house/", method = RequestMethod.POST)
    @Override
    public  Response<HouseEntity> house(@RequestBody HouseEntity emptyEntity){

        HouseEntity houseCondition = new HouseEntity();
        if(emptyEntity != null){
            Map<String,Object> conditionMap = emptyEntity.getProperties();
            String pageSize = conditionMap.get("pageSize") != null ? conditionMap.get("pageSize").toString() : "10";
            String pageNumber = conditionMap.get("pageNumber") != null ? conditionMap.get("pageNumber").toString() : "0";
            //房间名或者房间号
            String nameOrNum = conditionMap.get("searchStr") != null ? conditionMap.get("searchStr").toString() : "";
            //房屋状态
            String status = conditionMap.get("status") != null ? conditionMap.get("status").toString() : "";
            //即将退房 是一个日期 格式yyyy-MM-dd
            String checkoutDateStr = conditionMap.get("checkoutLimit") != null ? conditionMap.get("checkoutLimit").toString() : "";
            //超期账单 是一个日期 格式yyyy-MM-dd 暂时只支持房租
            String payDateStr = conditionMap.get("payLimit") != null ? conditionMap.get("payLimit").toString() : "";

            houseCondition.getProperties().put("pageSize",pageSize);
            houseCondition.getProperties().put("pageNumber",pageNumber);
            if(!StringUtils.isEmpty(nameOrNum)){
//                houseCondition.getProperties().put("name_like",nameOrNum);
                houseCondition.getProperties().put("houseNumber_like",nameOrNum);
            }
            if(!StringUtils.isEmpty(status)){
                houseCondition.getProperties().put("status",status);
            }
            if(!StringUtils.isEmpty(checkoutDateStr)){
                ContractEntity contractConditon = new ContractEntity();
                //选择退房选项，则它的合同状态必须是执行中(1)
                contractConditon.getProperties().put("status",1);
                contractConditon.getProperties().put("endDate_gt", Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()));
                LocalDateTime checkoutDate = LocalDateTime.parse(checkoutDateStr+"T23:59:59", DateTimeFormatter.ISO_LOCAL_DATE_TIME);
                contractConditon.getProperties().put("endDate_le", Date.from(checkoutDate.atZone(ZoneId.systemDefault()).toInstant()));

                List<ContractEntity> contractList = contractService.listAll(contractConditon);
                List<String> houseIdList = contractList.stream().map(contract -> {
                    return contract.getHouse().getId();
                }).collect(Collectors.toList());
                //返回结果为0条记录时，返回的就是某一个状态的所有房间所有记录有问题
                if(contractList.size()!=0){
                    houseCondition.getProperties().put("id_in" , houseIdList);
                }else{
                    //给他一个错误的房间状态，返回记录就为空
                    houseCondition.getProperties().put("status",7);
                }
            }
            if(!StringUtils.isEmpty(payDateStr)){
                //多少天内付款，房屋状态应该是已租赁:2代表以租赁，并且合同为执行中：1
                houseCondition.getProperties().put("status",2);
                ContractEntity contractConditon_pay = new ContractEntity();
                contractConditon_pay.getProperties().put("status",1);
                contractConditon_pay.getProperties().put("nextPayDate_gt", LocalDate.now().toString());
                contractConditon_pay.getProperties().put("nextPayDate_le", payDateStr);
                //将contractCondition超期放到houseCondition当中进行查询
                List<ContractEntity> contractList_pay = contractService.listAll(contractConditon_pay);
                List<String> houseIdList_pay = contractList_pay.stream().map(contract -> {
                    return contract.getHouse().getId();
                }).collect(Collectors.toList());
                //返回结果为0条记录时，返回的就是某一个状态的所有房间所有记录有问题
                if(contractList_pay.size()!=0){
                    houseCondition.getProperties().put("id_in" , houseIdList_pay);
                }else{
                    //给他一个错误的房间状态，返回记录就为空
                    houseCondition.getProperties().put("status",7);
                }
            }


        }
        return _pageAll(houseService,houseCondition);

    }


}
